<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="description" content="安全行业从业者，主要方向PC逆向附带安卓和Linux逆向，时不时喜欢写点BUG代码">
  <meta name="author" content="Cray">
  <meta name="keywords" content="">
  <title>常用代码 ~ 逆向安全博客</title>

  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/5.12.1/css/all.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/mdbootstrap/4.13.0/css/mdb.min.css"  >
<link rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/3.0.1/github-markdown.min.css"  >

<link rel="stylesheet" href="//at.alicdn.com/t/font_1067060_qzomjdt8bmp.css">



  <link rel="stylesheet" href="/lib/prettify/tomorrow.min.css"  >

<link rel="stylesheet" href="/css/main.css"  >


  <link rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css"  >


<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">


    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/">首页</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/archives/">归档</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/tags/">标签</a>
          </li>
        
          
          
          
          
          <li class="nav-item">
            <a class="nav-link" href="/links/">友链</a>
          </li>
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" false
      style="background: url('https://gitee.com//cve/BlogImg/raw/master/typora/wallhaven-wyk166.jpg') no-repeat center center;
      background-size: cover;">
    
        <div class="full-bg-img">
        <div class="mask rgba-black-light flex-center">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
                常用代码
              
            </span>

            
              <br>
              

              <p>
                
                  
                  &nbsp;<i class="far fa-chart-bar"></i>
                  <span class="post-count">
                    928 字
                  </span>&nbsp;
                

                
                  
                  &nbsp;<i class="far fa-clock"></i>
                  <span class="post-count">
                      5 分钟
                  </span>&nbsp;
                

                
                  <!-- 不蒜子统计文章PV -->
                  
                  &nbsp;<i class="far fa-eye" aria-hidden="true"></i>&nbsp;
                  <span id="busuanzi_container_page_pv">
                    <span id="busuanzi_value_page_pv"></span> 次
                  </span>&nbsp;
                
              </p>
            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="py-5 z-depth-3" id="board">
        <div class="post-content mx-auto" id="post">
          <div class="markdown-body">
            <p>[toc]</p>
<h3 id="Visual-Studio相关"><a href="#Visual-Studio相关" class="headerlink" title="Visual Studio相关"></a>Visual Studio相关</h3><h4 id="定义字符串常量的差别"><a href="#定义字符串常量的差别" class="headerlink" title="定义字符串常量的差别"></a>定义字符串常量的差别</h4><p>vs2019</p>
<pre><code class="c++">const WCHAR* Mes1 = L&quot;Hello world!&quot;;   //较为严格
WCHAR Mes2[] = L&quot;Hello world!&quot;;
WCHAR Mes3[] = &#123; L&#39;A&#39;,L&#39;B&#39;,L&#39;R&#39;,L&#39;l&#39;,0&#125;;//注意是单引号
char Mes4[] = &#123;&#39;a&#39;,&#39;b&#39;,&#39;v&#39;&#125;;</code></pre>
<p>vs2013</p>
<pre><code class="c">WCHAR* Mes1 = L&quot;Hello world!&quot;;
WCHAR Mes2[] = L&quot;Hello world!&quot;;
WCHAR Mes3[] = &#123; L&#39;A&#39;,L&#39;B&#39;,L&#39;R&#39;,L&#39;l&#39;,0&#125;;
char Mes4[] = &#123;&#39;a&#39;,&#39;b&#39;,&#39;v&#39;&#125;;</code></pre>
<h3 id="错误提示"><a href="#错误提示" class="headerlink" title="错误提示"></a>错误提示</h3><pre><code class="c++">#include &lt;windows.h&gt;
#include &lt;strsafe.h&gt;

void ErrorExit(const char* lpszFunction)
&#123;
    LPVOID lpMsgBuf;
    char Mes[1024] = &#123; 0, &#125;;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError();

    FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPSTR)&amp; lpMsgBuf,
        0, NULL);

    sprintf_s(Mes, &quot;%s failed with error 0x%x: %s&quot;, lpszFunction, dw, lpMsgBuf);
    MessageBoxA(NULL, Mes, &quot;failed&quot;, MB_OK);
    ExitProcess(dw);
&#125;

void main()
&#123;
    if (!GetProcessId(NULL))
        ErrorExit(&quot;GetProcessId&quot;);
&#125;</code></pre>
<h3 id="宏定义相关"><a href="#宏定义相关" class="headerlink" title="宏定义相关"></a>宏定义相关</h3><h4 id="定义函数"><a href="#定义函数" class="headerlink" title="定义函数"></a>定义函数</h4><pre><code>typedef NTSTATUS (WINAPI* FN_NtQueryInformationThread)(
    IN HANDLE               ThreadHandle,
    IN THREAD_INFORMATION_CLASS ThreadInformationClass,
    OUT PVOID               ThreadInformation,
    IN ULONG                ThreadInformationLength,
    OUT PULONG              ReturnLength OPTIONAL);

typedef struct _THREAD_BASIC_INFORMATION
&#123;
    NTSTATUS                ExitStatus;
    PVOID                   TebBaseAddress;
    int                        ClientId;
    KAFFINITY               AffinityMask;
    int                        Priority;
    int                        BasePriority;
    int                        v;
&#125; THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;

void Func()
&#123;
    FN_NtQueryInformationThread NtQueryInformationThread =(FN_NtQueryInformationThread)GetProcAddress(LoadLibrary(L&quot;Ntdll.dll&quot;), &quot;NtQueryInformationThread&quot;);
    NtQueryInformationThread(hOpenThread, (THREAD_INFORMATION_CLASS)0, &amp;threadBasicInfo, sizeof(threadBasicInfo), NULL);
&#125;</code></pre>
<h3 id="提权操作"><a href="#提权操作" class="headerlink" title="提权操作"></a>提权操作</h3><h4 id="令牌方式"><a href="#令牌方式" class="headerlink" title="令牌方式"></a>令牌方式</h4><pre><code class="c++">// 传入参数 SeDebugPrivilege，提升到调试权限

BOOL GrantPriviledge(WCHAR* PriviledgeName)
&#123;
    TOKEN_PRIVILEGES TokenPrivileges, OldPrivileges;
    DWORD             dwReturnLength = sizeof(OldPrivileges);
    HANDLE             TokenHandle = NULL;
    LUID             uID;

    if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &amp;TokenHandle))
    &#123;
        if (GetLastError() != ERROR_NO_TOKEN)
        &#123;
            return FALSE;
        &#125;
        if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &amp;TokenHandle))
        &#123;
            return FALSE;
        &#125;
    &#125;

    if (!LookupPrivilegeValue(NULL, PriviledgeName, &amp;uID))        // 通过权限名称查找uID
    &#123;
        CloseHandle(TokenHandle);
        return FALSE;
    &#125;

    TokenPrivileges.PrivilegeCount = 1;        // 要提升的权限个数
    TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    TokenPrivileges.Privileges[0].Luid = uID;

    if (!AdjustTokenPrivileges(TokenHandle, FALSE, &amp;TokenPrivileges, sizeof(TOKEN_PRIVILEGES), &amp;OldPrivileges, &amp;dwReturnLength))
    &#123;
        CloseHandle(TokenHandle);
        return FALSE;
    &#125;

    CloseHandle(TokenHandle);
    cout&lt;&lt; &quot;[+] AdjustTokenPrivileges to SeDebugPrivilege Success!&quot; &lt;&lt; endl;
    return TRUE;
&#125;
</code></pre>
<h4 id="RtlAdjustPrivilege"><a href="#RtlAdjustPrivilege" class="headerlink" title="RtlAdjustPrivilege"></a>RtlAdjustPrivilege</h4><pre><code class="c++">// 传入参数 SE_DEBUG_PRIVILEGE，提升到调试权限

#define SE_DEBUG_PRIVILEGE                (20L)

typedef
NTSTATUS(NTAPI * pfnRtlAdjustPrivilege)(
    UINT32 Privilege,
    BOOLEAN Enable,
    BOOLEAN Client,
    PBOOLEAN WasEnabled);

BOOL GrantPriviledge(IN UINT32 Priviledge)
&#123;
    pfnRtlAdjustPrivilege    RtlAdjustPrivilege = NULL;
    BOOLEAN                    WasEnable = FALSE;

    RtlAdjustPrivilege = (pfnRtlAdjustPrivilege)GetProcAddress(GetModuleHandle(L&quot;ntdll.dll&quot;), &quot;RtlAdjustPrivilege&quot;);
    if (RtlAdjustPrivilege == NULL)
    &#123;
        return FALSE;
    &#125;

    RtlAdjustPrivilege(Priviledge, TRUE, FALSE, &amp;WasEnable);

    return TRUE;
&#125;

RtlAdjustPrivilege</code></pre>
<h3 id="进程线程镜像"><a href="#进程线程镜像" class="headerlink" title="进程线程镜像"></a>进程线程镜像</h3><pre><code class="c++">// 使用ToolHelp系列函数

#include &lt;TlHelp32.h&gt;

BOOL GetProcessIdByProcessImageName(IN PWCHAR wzProcessImageName, OUT PUINT32 ProcessId)
&#123;
    HANDLE            ProcessSnapshotHandle = INVALID_HANDLE_VALUE;
    PROCESSENTRY32    ProcessEntry32 = &#123; 0 &#125;;

    ProcessEntry32.dwSize = sizeof(PROCESSENTRY32);        // 初始化PROCESSENTRY32结构

    ProcessSnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    // 给系统所有的进程快照
    if (ProcessSnapshotHandle == INVALID_HANDLE_VALUE)
    &#123;
        return FALSE;
    &#125;

    if (Process32First(ProcessSnapshotHandle, &amp;ProcessEntry32))        // 找到第一个
    &#123;
        do
        &#123;
            if (lstrcmpi(ProcessEntry32.szExeFile, wzProcessImageName) == 0)        // 不区分大小写
            &#123;
                *ProcessId = ProcessEntry32.th32ProcessID;
                break;
            &#125;
        &#125; while (Process32Next(ProcessSnapshotHandle, &amp;ProcessEntry32));
    &#125;

    CloseHandle(ProcessSnapshotHandle);
    ProcessSnapshotHandle = INVALID_HANDLE_VALUE;

    if (*ProcessId == 0)
    &#123;
        return FALSE;
    &#125;
    return TRUE;
&#125;

</code></pre>
<h3 id="注册表"><a href="#注册表" class="headerlink" title="注册表"></a>注册表</h3><pre><code class="c++">int main()
&#123;
    LSTATUS Status = 0;
#ifdef _WIN64
    　　　　WCHAR*    wzSubKey = L&quot;SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows&quot;;
#else
    　　　　WCHAR*    wzSubKey = L&quot;SOFTWARE\\WOW6432Node\\Microsoft\\Windows NT\\CurrentVersion\\Windows&quot;;
#endif // _WIN64

    HKEY    hKey = NULL;

    // 打开注册表
    Status = RegOpenKeyExW(HKEY_LOCAL_MACHINE,        // 要打开的主键
        wzSubKey,            // 要打开的子键名字地址
        0,                    // 保留，传0
        KEY_ALL_ACCESS,        // 打开的方式
        &amp;hKey);                // 返回的子键句柄
    if (Status != ERROR_SUCCESS)
    &#123;
        return 0;
    &#125;

    WCHAR*    wzValueName = L&quot;AppInit_DLLs&quot;;
    DWORD    dwValueType = 0;
    UINT8    ValueData[MAX_PATH] = &#123; 0 &#125;;
    DWORD    dwReturnLength = 0;

    // 查询注册表
    Status = RegQueryValueExW(hKey,        // 子键句柄
        wzValueName,        // 待查询键值的名称
        NULL,                // 保留
        &amp;dwValueType,        // 数据类型
        ValueData,            // 键值
        &amp;dwReturnLength);


    WCHAR    wzDllFullPath[MAX_PATH] = &#123; 0 &#125;;
    GetCurrentDirectoryW(MAX_PATH, wzDllFullPath);

#ifdef _WIN64
    wcscat_s(wzDllFullPath, L&quot;\\x64NormalDll.dll&quot;);
#else
    wcscat_s(wzDllFullPath, L&quot;\\x86NormalDll.dll&quot;);
#endif

    // 设置键值
    Status = RegSetValueExW(hKey,
        wzValueName,
        NULL,
        dwValueType,
        (CONST BYTE*)wzDllFullPath,
        (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR));
    if (Status != ERROR_SUCCESS)
    &#123;
        return 0;
    &#125;

    wzValueName = L&quot;LoadAppInit_DLLs&quot;;
    DWORD    dwLoadAppInit = 1;

    // 查询注册表
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &amp;dwValueType, ValueData, &amp;dwReturnLength);

    // 设置键值
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&amp;dwLoadAppInit, sizeof(DWORD));
    if (Status != ERROR_SUCCESS)
    &#123;
        return 0;
    &#125;

    printf(&quot;Input Any Key To Resume\r\n&quot;);

    getchar();
    getchar();

    // 恢复键值
    dwLoadAppInit = 0;
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &amp;dwValueType, ValueData, &amp;dwReturnLength);
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)&amp;dwLoadAppInit, sizeof(DWORD));

    wzValueName = L&quot;AppInit_DLLs&quot;;
    ZeroMemory(wzDllFullPath, (lstrlen(wzDllFullPath) + 1) * sizeof(WCHAR));
    Status = RegQueryValueExW(hKey, wzValueName, NULL, &amp;dwValueType, ValueData, &amp;dwReturnLength);
    Status = RegSetValueExW(hKey, wzValueName, NULL, dwValueType, (CONST BYTE*)wzDllFullPath, 0);


    return 0;
&#125;</code></pre>

            <hr>
          </div>
          <br>
          <div>
            <p>
            
            
              <span>
                <i class="iconfont icon-tag"></i>
                
                  <a class="hover-with-bg" href="/tags/%E5%BC%80%E5%8F%91/">开发</a>
                
              </span>
            
            </p>
            
              <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://zh.wikipedia.org/wiki/Wikipedia:CC_BY-SA_3.0%E5%8D%8F%E8%AE%AE%E6%96%87%E6%9C%AC" rel="nofollow noopener noopener">CC BY-SA 3.0协议</a> 。转载请注明出处！</p>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container">
        <div id="toc">
  <p class="h5"><i class="far fa-list-alt"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>
      </div>
    
  </div>
</div>

<!-- custom -->


<!-- Comments -->
<div class="col-lg-7 mx-auto nopadding-md">
  <div class="container comments mx-auto" id="comments">
    
      <br><br>
      
      
  <div class="disqus" style="width:100%">
    <div id="disqus_thread"></div>
    <script>
      var disqus_config = function () {
        this.page.url = 'http://cve.gitee.io/cve/2020/06/15/常用代码/';
        this.page.identifier = '/2020/06/15/常用代码/';
      };
      var oldLoad = window.onload;
      window.onload = function () {
        var d = document, s = d.createElement('script');
        s.type = 'text/javascript';
        s.src = '//' + 'crayon-1' + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
      };
    </script>
    <noscript>Please enable JavaScript to view the <a target="_blank" href="https://disqus.com/?ref_noscript" rel="nofollow noopener noopener">comments
        powered by Disqus.</a></noscript>
  </div>


    
  </div>
</div>

    
  </main>

  
    <a class="z-depth-1" id="scroll-top-button" href="#" role="button">
      <i class="fa fa-chevron-up scroll-top-arrow" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  <footer class="mt-5">
  <div class="text-center py-3">
    <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><b>Hexo</b></a>
    <i class="iconfont icon-love"></i>
    <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"> <b>Fluid</b></a>
    <br>

    
  
    <!-- 不蒜子统计PV -->
    
    &nbsp;<span id="busuanzi_container_site_pv"></span>总访问量 
          <span id="busuanzi_value_site_pv"></span> 次&nbsp;
  
  
    <!-- 不蒜子统计UV -->
    
    &nbsp;<span id="busuanzi_container_site_uv"></span>总访客数 
            <span id="busuanzi_value_site_uv"></span> 人&nbsp;
  
  <br>



    


    <!-- cnzz Analytics icon -->
    

  </div>
</footer>

<!-- SCRIPTS -->
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script src="https://cdn.staticfile.org/popper.js/1.16.1/umd/popper.min.js" ></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.staticfile.org/mdbootstrap/4.13.0/js/mdb.min.js" ></script>
<script src="/js/main.js" ></script>


  <script src="/js/lazyload.js" ></script>



  
  <script src="https://cdn.staticfile.org/tocbot/4.10.0/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var navHeight = $('#navbar').height();
      var toc = $('#toc');
      var main = $('main');
      var tocT = navHeight + (toc.offset().top - main.offset().top);
      var tocLimMin = main.offset().top - navHeight;
      var tocLimMax = $('#comments').offset().top - navHeight;
      $(window).scroll(function () {
        var scroH = document.body.scrollTop + document.documentElement.scrollTop;
        if (tocLimMin <= scroH && scroH <= tocLimMax) {
          toc.css({
            'display': 'block',
            'position': 'fixed',
            'top': tocT,
          });
        } else if (scroH <= tocLimMin) {
          toc.css({
            'position': '',
            'top': '',
          });
        } else if (scroH > tocLimMax) {
          toc.css('display', 'none');
        }
      });
      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '.post-content',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        scrollSmooth: true,
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc > p').css('visibility', 'visible');
      }
    });
  </script>







  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>


<!-- Plugins -->



  <script src="https://cdn.staticfile.org/prettify/188.0.0/prettify.min.js" ></script>
  <script>
    $(document).ready(function () {
      $('pre').addClass('prettyprint  linenums');
      prettyPrint();
    })
  </script>





  <script src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      getSearchFile(path);
      this.onclick = null
    }
  </script>



  <script src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <script>
    $("#post img:not(.no-zoom img, img[no-zoom])").each(
      function () {
        var element = document.createElement("a");
        $(element).attr("data-fancybox", "images");
        $(element).attr("href", $(this).attr("src"));
        $(this).wrap(element);
      }
    );
  </script>












</body>
</html>
